package com.craftyworks.alejandro.api;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class C2DMPush {
    
    public final static String C2DM_SERVER_URL = "https://android.apis.google.com/c2dm/send";
    
    private final Logger logger = LoggerFactory.getLogger(getClass());

    private GoogleAuthorization googleAuth;
    
    private HttpClientTemplate httpClient;
    
    public void setGoogleAuth(GoogleAuthorization googleAuth) {
        this.googleAuth = googleAuth;
    }
    
    public void setHttpClient(HttpClientTemplate httpClient) {
        this.httpClient = httpClient;
    }
    
    public void sendMessage(String registrationId, Map<String, String> data) throws IOException {
        StringBuilder sb = new StringBuilder("");
        sb.append("registration_id=").append(registrationId);
        sb.append("&collapse_key=").append(RandomStringUtils.randomAlphanumeric(24));
        sb.append("&delay_while_idle=1");
        for(Entry<String, String> entry : data.entrySet()) {
            sb.append("&data.").append(entry.getKey()).append("=").append(entry.getValue());
        }
        
        Map<String, String> header = new HashMap<String, String>();
        header.put("Authorization", "GoogleLogin auth=" + googleAuth.getAuthorizationToken());
        
        HttpResponse response = httpClient.sendHttpRequest(C2DM_SERVER_URL, header, sb.toString());
        logger.debug("C2DM message push result : {}", EntityUtils.toString(response.getEntity()));
    }
}
